package models

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	"github.com/gomodule/redigo/redis"
	redisC "kop/libs/redis"
	"kop/pb"
)

func GetUserID(token string) (int32, error) {

	var r = redisC.Conn()
	defer r.Close()

	res, err := redis.Int(r.Do("GET", token))
	return int32(res), err
}

// save token in redis
func SaveUser(s string, user *pb.User) error {

	var r = redisC.Conn()
	defer r.Close()

	var b, _ = proto.Marshal(user)
	var _, err = r.Do("SET", s, b, "EX", 86400*14)
	_, _ = r.Do("SET", fmt.Sprintf("USER.%d", user.UserID), s, "EX", 86400*14)
	return err
}

func GetUser(s string) (user pb.User, err error) {

	var r = redisC.Conn()
	defer r.Close()

	if b, err := redis.Bytes(r.Do("GET", s)); err != nil {
		return user, err
	} else {
		return user, proto.Unmarshal(b, &user)
	}
}
